package com.diaohaiwen.framework.db.config;

import cn.hutool.core.util.ClassUtil;
import com.diaohaiwen.framework.db.GlobalListener;
import com.diaohaiwen.framework.db.obj.BaseCUModel;
import com.diaohaiwen.framework.db.obj.BaseCModel;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.spring.boot.ConfigurationCustomizer;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.springframework.context.annotation.Configuration;

import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Configuration
public class DatabaseConfig implements MyBatisFlexCustomizer, ConfigurationCustomizer {

    @Override
    public void customize(FlexConfiguration configuration) {
        // 在这里为 configuration 进行配置
        configuration.setLogImpl(StdOutImpl.class);
    }

    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {

        Class<?>[] baseModelClass = getModelClass(BaseCUModel.class);
        flexGlobalConfig.registerInsertListener(new GlobalListener(), baseModelClass);
        flexGlobalConfig.registerUpdateListener(new GlobalListener(), baseModelClass);

        Class<?>[] logModelClasses = getModelClass(BaseCModel.class);
        flexGlobalConfig.registerInsertListener(new GlobalListener(), logModelClasses);

    }

    private Class<?>[] getModelClass(Class<?> supperClass) {
        Set<Class<?>> classes = ClassUtil.scanPackage("com.diaohaiwen")
                .stream().filter(sonClass -> {
                    boolean allAssignableFrom = ClassUtil.isAllAssignableFrom(new Class[]{supperClass},
                            new Class[]{sonClass});
                    //要将 本身排除
                    return allAssignableFrom && sonClass != supperClass;
                }).collect(Collectors.toSet());

        log.info("{} >>> {}", supperClass, classes.size());

        return classes.toArray(new Class<?>[0]);


    }

}
